package socketNotes;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class socketDemo {
    public void context() {
        String host = "www.baidu.com";
        int port = 80;
        String filePath = "src/main/java/socketNotes/socket.txt";

        try (
                Socket socket = new Socket(InetAddress.getByName(host), port);
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                InputStream is = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));

        ) {
            bw.write("GET / HTTP/1.1\r\n");
            bw.write("Connection: Keep-Alive\r\n");
            bw.write("Host: www.baidu.com\r\n");
            bw.write("Connection: Keep-Alive\r\n\r\n");
            bw.flush();
            socket.shutdownOutput();
            String str = null;
            while ((str = br.readLine()) != null) {
                bufferedWriter.write(str);
                bufferedWriter.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
